<template>
    <!-- 外层容器：使用 ref 定位当前组件实例 -->
    <div ref="dropdownRef" class="relative inline-block dropdown-container" @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave" @click="handleClick">
        <slot></slot>
        <div :style="{ left: `${horizontalOffsetValue}px`, top: `calc(100% + ${verticalOffsetValue}px)` }" class="absolute z-[999] bg-white dark:bg-[#1e2329] dark:shadow-[0_0px_2px_rgba(255,255,255,0.15)] rounded-md shadow-[0_0px_10px_rgba(0,0,0,0.15)] border border-gray-200 
             overflow-hidden transition-all duration-200 ease-in-out origin-top-left " :class="[
                isShow ? 'opacity-100 scale-100 visible' : 'opacity-0 scale-95 invisible',
                isShow ? '' : 'pointer-events-none',
                placement === 'right' ? 'left-auto right-0 origin-top-right' : ''
            ]" @click.stop>
            <div>
                <slot name="content"></slot>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, defineProps, withDefaults, onUnmounted } from 'vue';

const timer = ref<number | null>(null);
let outsideClickHandler: ((e: MouseEvent) => void) | null = null;
// 关键：用 ref 定位当前组件的 DOM 元素（每个实例独立）
const dropdownRef = ref<HTMLDivElement | null>(null);

interface DropdownProps {
    placement?: 'left' | 'right';
    horizontalOffsetValue?: number;
    verticalOffsetValue?: number;
    clickTrigger?: boolean;
    // 新增：循环渲染时的唯一标识（可选，但推荐）
    id?: string;
}

const props = withDefaults(defineProps<DropdownProps>(), {
    placement: 'left',
    horizontalOffsetValue: 0,
    verticalOffsetValue: 0,
    clickTrigger: false,
    id: ''
});

const emit = defineEmits(['mouseenter', 'mouseleave', 'click']);
const isShow = ref(false);

// Hover 逻辑（保持不变）
const handleMouseEnter = () => {
    if (props.clickTrigger) return;
    timer.value && clearTimeout(timer.value);
    isShow.value = true;
    emit('mouseenter');
};

const handleMouseLeave = () => {
    if (props.clickTrigger) return;
    timer.value && clearTimeout(timer.value);
    timer.value = window.setTimeout(() => {
        isShow.value = false;
        emit('mouseleave');
    }, 200);
};

// 点击逻辑（核心修复：每个组件实例独立管理事件）
const handleClick = () => {
    if (!props.clickTrigger) return;

    timer.value && clearTimeout(timer.value);
    isShow.value = !isShow.value;
    emit('click', isShow.value);

    if (isShow.value) {
        // 为每个组件实例创建独立的外部点击处理器
        outsideClickHandler = (e: MouseEvent) => {
            // 通过 ref 获取当前组件的 DOM 元素（确保唯一性）
            const currentEl = dropdownRef.value;
            if (currentEl && !currentEl.contains(e.target as Node)) {
                isShow.value = false;
                removeOutsideClickListener();
            }
        };
        document.addEventListener('click', outsideClickHandler);
    } else {
        removeOutsideClickListener();
    }
};

// 移除监听时精准移除当前组件的事件处理器
const removeOutsideClickListener = () => {
    if (outsideClickHandler) {
        document.removeEventListener('click', outsideClickHandler);
        outsideClickHandler = null;
    }
};

// 组件卸载时必须清理当前实例的事件监听
onUnmounted(() => {
    timer.value && clearTimeout(timer.value);
    removeOutsideClickListener();
});
</script>

<style scoped>
.dropdown-container {
    /* z-index: 50; */
}
</style>